package com.explorati.interview.interview.chaptereight;

public class Store {

	private final int MAX_SIZE;
	private int count;

	public Store(int n) {
		MAX_SIZE = n;
		count = 0;
	}

	// 往仓库加货物的方法
	public synchronized void add() {
		// 判断仓库是否已满
		while (count >= MAX_SIZE) {
			System.out.println("已经满了");
			try {
				// 若满了，则进入等待池
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		count++;
		System.out.println(Thread.currentThread().getName() + "put" + count);
		this.notifyAll();
	}

	public synchronized void remove() {
		while (count <= 0) {
			System.out.println("空了");
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println(Thread.currentThread().getName() + "get" + count);
		count--;
		// 仓库没装满，通知生产者添加货物
		this.notify();
	}

	public static void main(String[] args) {
		Store s = new Store(5);
		Thread pro = new Producer(s);
		Thread con = new Consumer(s);
		Thread pro2 = new Producer(s);
		Thread con2 = new Consumer(s);

		pro.setName("peoducer");
		con.setName("consumer");
		pro2.setName("producer2");
		con.setName("consumer2");

		pro.start();
		pro2.start();
		con.start();
		con2.start();
	}
}
